import tkinter as tk


class CustomDialog(tk.Toplevel):
    def __init__(self, parent, title=None, message=None):
        super().__init__(parent)
        self.transient(parent)
        self.title(title)
        self.parent = parent
        self.result = None

        # 设置窗口体
        body = tk.Frame(self)
        self.initial_focus = self.body(body, message)
        body.pack(padx=5, pady=5)

        # 添加按钮
        self.buttonbox()

        self.grab_set()
        if not self.initial_focus:
            self.initial_focus = self
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.center_to_parent()

        self.initial_focus.focus_set()
        self.wait_window(self)

    def body(self, master, message):
        # 创建消息文本
        label = tk.Label(master, text=message)
        label.pack(padx=5, pady=5)

    def buttonbox(self):
        box = tk.Frame(self)

        ok_button = tk.Button(
            box, text="OK", width=10, command=self.ok, default=tk.ACTIVE
        )
        ok_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)

        box.pack()

    def ok(self, event=None):
        self.withdraw()
        self.update_idletasks()
        self.apply()
        self.cancel()

    def apply(self):
        self.result = True  # 或者其他逻辑

    def cancel(self, event=None):
        self.parent.focus_set()
        self.destroy()

    def center_to_parent(self):
        self.update_idletasks()  # 确保获得最新的信息
        parent_x = self.parent.winfo_x()
        parent_y = self.parent.winfo_y()
        parent_width = self.parent.winfo_width()
        parent_height = self.parent.winfo_height()

        width = self.winfo_reqwidth()
        height = self.winfo_reqheight()

        x = parent_x + (parent_width // 2) - (width // 2)
        y = parent_y + (parent_height // 2) - (height // 2)

        self.geometry("+{}+{}".format(x, y))
